package com.async.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * 异步任务总配置类
 * </p>
 * @author yang
 * @date 2024/5/20
 */
@Configuration
@Slf4j
@ComponentScan("com.async")
@ConditionalOnProperty(prefix = "async", value = "enabled", havingValue = "true")
@EnableConfigurationProperties({AsyncDataSourceProperties.class,AsyncThreadProperties.class})
public class AsyncConfig {
    @Bean(name = "asyncJdbcTemplate")
    public JdbcTemplate jdbcTemplate(AsyncDataSourceProperties asyncDataSourceProperties) throws Exception {
        log.info("异步数据源开始装配:{}",asyncDataSourceProperties);
        return new JdbcTemplate(DruidDataSourceFactory.createDataSource(asyncDataSourceProperties));
    }

    @Bean(name = "asyncExecute")
    public Executor asyncExecutor(AsyncThreadProperties asyncThreadProperties) {
        log.info("异步线程开始装配:{}",asyncThreadProperties);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(asyncThreadProperties.getCorePoolSize());
        // 最大线程数
        executor.setMaxPoolSize(asyncThreadProperties.getMaxPoolSize());
        // 队列容量
        executor.setQueueCapacity(asyncThreadProperties.getQueueCapacity());
        // 线程空闲时间
        executor.setKeepAliveSeconds(asyncThreadProperties.getKeepAliveSeconds());
        // 线程名字前缀
        executor.setThreadNamePrefix("asyncExecute-");
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
